package com.daisuxia.risk.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.dao.IRiskCreditLogDao;
import com.daisuxia.risk.dao.IRiskCreditUserDao;
import com.daisuxia.risk.dao.IRiskRuleCalDao;
import com.daisuxia.risk.pojo.RiskCreditLog;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskManageRule;
import com.daisuxia.risk.pojo.RiskRuleCal;
import com.daisuxia.risk.pojo.RiskRuleProperty;
import com.daisuxia.risk.utils.BeanReflectUtil;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.RiskCreditUserUtil;
import com.daisuxia.risk.utils.ThreadPool;
import com.daisuxia.risk.utils.ThreadPool2;
import com.daisuxia.ts.service.ITsOrdersService;
import com.daisuxia.web.dao.IPaginationDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IInfoIndexService;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.JedisDataClientFK;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.ThreadPool3;

import redis.clients.jedis.JedisCluster;

/**
 * zhangsh
 * 类描述： 此类的所有更新方法，都会先调用insert方法.insert方法内部逻辑是，先根据userId查询数据库中是否有该记录<br>
 * 如果没有该记录则插入一条仅包含userId、用户名、身份证号码、性别、年龄的数据 <br>
 * 创建人：fanyinchuan<br>
 * 创建时间：2016-12-12 下午05:14:12 <br>
 */
@Service
public class RiskCreditUserService implements IRiskCreditUserService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskCreditUserDao riskCreditUserDao;
	@Autowired
	private IRiskCreditLogDao riskCreditLogDao;
	@Autowired
	private IZmxyService zmxyService;
	@Autowired
	private ITdService tdService;
	@Autowired
	private IBqsService bqsService;
	@Autowired
	private IJyzxService jyzxService;
	@Autowired
	private IJxlMgService jxlMgService;
	@Autowired
	private IInfoIndexService infoIndexService;
	@Autowired
	private IRiskManageRuleService riskManageRuleService;
	@Autowired
	private IRiskRuleCalDao riskRuleCalDao;
	@Autowired
	private IInfoIndexService indexService;
	@Autowired
	private IYxService yxService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IPaginationDao paginationDao;
	@Autowired
	private IZzcService zzcService;
	@Autowired
	private IShService shService;
	@Autowired
	private ITsOrdersService tsOrdersService;
	@Autowired
	JedisCluster jedisCluster;
	//写入key
	@Value("#{propSettings['redis.inputkey']}")
	private String riskIt;

	//读取key
	@Value("#{propSettings['redis.outputkey']}")
	private String riskOt;

	@Override
	public int updateUserMyHb(RiskCreditUser riskCreditUser) {
		return riskCreditUserDao.updateUserMyHb(riskCreditUser);
	}

	@Override
	public void updateZm(RiskCreditUser riskCreditUser) {
		riskCreditLogDao
				.insert(new RiskCreditLog(riskCreditUser.getUserId(), riskCreditUser.toString(), ConstantRisk.GET_INDUSTY, ConstantRisk.ZMXY));
		riskCreditUserDao.updateUserZmIndusty(riskCreditUser);
		riskCreditUserDao.updateNewFlag(riskCreditUser.getUserId());
	}

	/**
	 * 重新计算用户借款额度，计算机审额度,刚认证完的用户调用和申请借款时调用
	 *
	 * @param id 征信主键ID<br>
	 */
	public String updateCalUserMoney(Integer id, String dbTime) {
		String result = null;
		try {
			RiskCreditUser riskCreditUser = riskCreditUserDao.findById(id);
			riskCreditUser.setJxlDetail(riskCreditUserDao.findDetailById(riskCreditUser.getUserId()));
			List<RiskManageRule> root = riskManageRuleService.findAllByRootType(RiskManageRule.ROOT_TYPE_ROOT_ED);
			if (root != null && root.size() > 0) {
				Map<String, RiskManageRule> allRiskMap = SysCacheUtils.getAllRule();
				Map<String, String> baseMap = SysCacheUtils.getBaseRule();
				Map<String, String> propertyMap = SysCacheUtils.getConfigMap(ConstantRisk.BASE_RULE_PROPERTY);
				if (propertyMap != null && propertyMap.size() > 0) {
					for (String key : propertyMap.keySet()) {
						try {
							Object value = BeanReflectUtil.invokeGetMethod(RiskCreditUser.class, propertyMap.get(key), riskCreditUser);
							baseMap.put(key, value + "");
						} catch (Exception e) {
							logger.error("key error key=" + key, e);
						}
					}
					RiskCreditUserUtil.getInstance().findSon(root, allRiskMap, null);
					RiskManageRule riskManageRule = root.get(0);
					List<RiskRuleCal> calList = new ArrayList<RiskRuleCal>();
					RiskCreditUserUtil.getInstance().calSon2Parent(root, riskManageRule, baseMap, id, riskCreditUser.getAssetId(),
							riskCreditUser.getUserId(), calList);
					HashMap<String, Object> list = new HashMap<String, Object>();
					list.put("dbTime", dbTime);
					list.put("list", calList);
					riskRuleCalDao.batchInsert(list);
					riskCreditUser.setRiskCalSuf(dbTime);
					riskCreditUserDao.updateSuf(riskCreditUser);
					result = riskManageRule.getFormula();
					riskCreditUser.setAmountMax(new BigDecimal(result));
					riskCreditUserDao.updateUserMoney(riskCreditUser);
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("userId", riskCreditUser.getUserId());
					// indexService.changeUserAmount(map);
					logger.info("after update user amount");
					map.put("newAmountMax", new BigDecimal(result).multiply(new BigDecimal(100)).intValue());
					borrowOrderService.changeUserLimit(map);
					logger.info("after insert limit");
					riskCreditUserDao.updateMoney(riskCreditUser);
				}
			}
		} catch (Exception e) {
			logger.error("updateCalUserMoney error id=" + id, e);
		}
		return result;
	}

	/**
	 * 计算用户的借款额度
	 *
	 * @param riskCreditUser
	 */
	@Override
	public void updateBorrowMoney(RiskCreditUser riskCreditUser2) {
		try {
			RiskCreditUser tmp = new RiskCreditUser();
			tmp.setUserId(riskCreditUser2.getUserId());
			tmp.setAssetId(0);
			Integer id = riskCreditUserDao.findOneCal(tmp);
			if (id == null) {
				// 查询数据库没有已计算记录则插入
				riskCreditUser2.setAssetId(ConstantRisk.NO_ID);
				riskCreditUser2.setLastDays(-1);
				riskCreditUser2.setRiskStatus(5);
				riskCreditUserDao.insertCalMoney(riskCreditUser2);
				id = riskCreditUser2.getId();
			}
			//从征信机构获取基础数据
			ServiceResult serviceResult = updateSendZx(id);
			if (serviceResult.isSuccessed()) {
				String calMoneyAmount=updateCalUserMoney(id, riskRuleCalDao.findDbTime());
				logger.info("caled money amount is  "+calMoneyAmount+", riskCreditID= "+id+", userId = "+riskCreditUser2.getUserId());
			} else if ("300".equals(serviceResult.getCode())) {
				// 更新额度
				String value = "0";
				riskCreditUser2.setAmountMax(new BigDecimal(value));
				riskCreditUserDao.updateUserMoney(riskCreditUser2);
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("userId", riskCreditUser2.getUserId());
				logger.info("after update user amount");
				// 系统最大额度
				Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.SYS_FEE);
				Integer sysAmountMax = Integer.parseInt(keys.get("max_amount_sys")) / 100;
				Integer currentValue=Integer.parseInt(value) / 100;
				if(currentValue>sysAmountMax){
					logger.info("new money amount great than sysAmountMax "+riskCreditUser2.getUserId()+", name = "+riskCreditUser2.getUserName());
					value=String.valueOf(sysAmountMax);
				}
				map.put("newAmountMax", new BigDecimal(value));
				borrowOrderService.changeUserLimit(map);
				logger.info("after insert limit");
				riskCreditUserDao.updateMoney(riskCreditUser2);
			}

		} catch (Exception e) {
			logger.error("updateBorrowMoney error riskCreditUser2=" + riskCreditUser2.toString(), e);
		}
	}

	/**
	 * 辅助计算额度时发送征信请求，成功的记录不再请求
	 *
	 * @param id
	 * @return 500是未知异常，200是全部接口正常并且通过准入原则；300是命中准入原则
	 */
	public ServiceResult updateSendZx(Integer id) {
		ServiceResult serviceResult2 = new ServiceResult("500", "未知异常");
		String msg = null;
		try {
			RiskCreditUser riskCreditUser = riskCreditUserDao.findById(id);
			riskCreditUser.setJxlDetail(riskCreditUserDao.findDetailById(riskCreditUser.getUserId()));
			Integer userId = riskCreditUser.getUserId();
			StringBuffer errorMsg = new StringBuffer("");
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("userName", riskCreditUser.getUserName());
			params.put("cardNum", riskCreditUser.getCardNum());
			params.put("userPhone", riskCreditUser.getUserPhone());
			params.put("userId", userId);
			String reportId = riskCreditUser.getTdReportId();

			Integer tdStatus = riskCreditUser.getTdStatus();
			Integer bqsStatus = riskCreditUser.getBqsStatus();
			Integer jyStatus = riskCreditUser.getJyStatus();
			Integer mgStatus = riskCreditUser.getMgStatus();
			Integer zmStatus = riskCreditUser.getZmStatus();
			Integer yxStatus = riskCreditUser.getYxStatus();
			Integer zzcStatus = riskCreditUser.getZzcStatus();
			Integer shStatus = riskCreditUser.getShStatus();
			Date zzcBlackTime = riskCreditUser.getZzcBlackTime();
			HashMap<String, Object> params2 = new HashMap<String, Object>();
			params2.putAll(params);
			if (zzcBlackTime==null) {
//				if (false) {
				ServiceResult serviceResult = zzcService.getFqz(params2);
				if (serviceResult.isSuccessed()) {
					//JSONObject jsonObject = JSONObject.fromObject(serviceResult.getMsg());
//					String rt = jsonObject.getString("blacklist");
					//params2.put("zzcId", zzcId);
					//serviceResult = zzcService.findFqz(params2);
					if (serviceResult.isSuccessed()) {
						zzcStatus = ConstantRisk.INTERFACE_SUC;
						RiskCreditUser riskCreditUser2 = RiskCreditUserUtil.getInstance().createZzc(id, serviceResult.getMsg());
						
						riskCreditUserDao.updateZzc(riskCreditUser2);
						if (riskCreditUser2.getZzcBlack().intValue() == 1) {
							msg = "命中中智诚黑名单";
						} else if (riskCreditUser2.getZzcFqz().intValue() == 1) {
							msg = "命中中智诚反欺诈高";
						}
					} else {
						errorMsg.append("中智诚反欺诈查询失败;");
					}
				} else {
					errorMsg.append("中智诚反欺诈查询失败;");
				}
			}
			RiskCreditUser tmp = riskCreditUserDao.findUserDetail(riskCreditUser.getUserId());
			BigDecimal zmScore = tmp.getZmScore();
			Integer zmIndustyBlack = tmp.getZmIndustyBlack();
			Integer zmOver = tmp.getZmOver();
			Integer zmNoPayOver = tmp.getZmNoPayOver();
			riskCreditUser.setId(id);
			riskCreditUser.setUserId(riskCreditUser.getUserId());
			riskCreditUser.setZmScore(zmScore);
			riskCreditUser.setZmIndustyBlack(zmIndustyBlack);
			riskCreditUser.setZmOver(zmOver);
			riskCreditUser.setZmNoPayOver(zmNoPayOver);
			riskCreditUserDao.updateZm(riskCreditUser);
			zmStatus = ConstantRisk.INTERFACE_SUC;
			if (yxStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue()) {
				ServiceResult serviceResult = yxService.sendYx(params);
				if (serviceResult.isSuccessed()) {
					RiskCreditUser riskCreditUser2 = RiskCreditUserUtil.getInstance().createYx(userId, serviceResult.getMsg());
					if (riskCreditUser2 != null) {
						riskCreditUser2.setId(id);
						riskCreditUserDao.updateYx(riskCreditUser2);
						if (riskCreditUser2.getYxFxNum().intValue() > 0) {
							msg = "命中宜信风险名单";
						}
					} else {
						logger.info("sendZx create yx return null");
					}
				}
			}
			if (StringUtils.isBlank(msg)) {
				// 白骑士黑名单接口
				if (bqsStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue()) {
					ServiceResult serviceResult = bqsService.getRisk(params2);
					if (serviceResult.isSuccessed()) {
						riskCreditUser = RiskCreditUserUtil.getInstance().createBqs(id, serviceResult.getMsg());
						if (riskCreditUser != null) {
							bqsStatus = ConstantRisk.INTERFACE_SUC;
							riskCreditUserDao.updateBqs(riskCreditUser);
							if (riskCreditUser.getBqsBlack().intValue() == 2) {
								msg = "命中白骑士黑名单";
							}
						} else {
							errorMsg.append("本地解析白骑士征信信息错误;");
						}
					} else {
						errorMsg.append("查询白骑士征信信息错误:" + serviceResult.getMsg() + ";");
					}
				}
			}
			//91征信
			if (StringUtils.isBlank(msg)) {
				if (jyStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue()) {
					ServiceResult serviceResult = jyzxService.getBorrow(params2);
					if (serviceResult.isSuccessed()) {
						riskCreditUser = RiskCreditUserUtil.getInstance().createJyzx(id, serviceResult.getMsg());
						if (riskCreditUser != null) {
							jyStatus = ConstantRisk.INTERFACE_SUC;
							riskCreditUserDao.updateJy(riskCreditUser);
							if (riskCreditUser.getJyOverNum().intValue() > 0) {
								msg = "命中91逾期记录";
							}
						} else {
							errorMsg.append("本地解析91征信信息错误;");
						}
					} else {
						errorMsg.append("查询91征信信息错误:" + serviceResult.getMsg() + ";");
					}
				}
			}
			//聚信立
			if (StringUtils.isBlank(msg)) {
				if (mgStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue()) {
					ServiceResult serviceResult = jxlMgService.getDetail(params2);
					if (serviceResult.isSuccessed()) {
						riskCreditUser = RiskCreditUserUtil.getInstance().createMg(id, serviceResult.getMsg());
						if (riskCreditUser != null) {
							mgStatus = ConstantRisk.INTERFACE_SUC;
							riskCreditUserDao.updateMg(riskCreditUser);
							if (riskCreditUser.getMgBlack().intValue() == 1) {
								msg = "命中蜜罐黑名单";
							}
						} else {
							errorMsg.append("本地解析密罐征信信息错误;");
						}
					} else {
						errorMsg.append("查询密罐征信信息错误:" + serviceResult.getMsg() + ";");
					}
				}
			}
			//TODO
			if (StringUtils.isBlank(msg)) {
				if (shStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue()) {
//					ServiceResult serviceResult = shService.getFqz(params2);
//					if (serviceResult.isSuccessed()) {
//						riskCreditUser = RiskCreditUserUtil.getInstance().createSh(id, serviceResult.getMsg());
//						if (riskCreditUser != null) {
//							shStatus = ConstantRisk.INTERFACE_SUC;
//							riskCreditUserDao.updateSh(riskCreditUser);
//							if (riskCreditUser.getShFqz().intValue() == 3) {
//								// 66666暂时不使用算话的结果，先注释掉，用的时候取消注释
//								// msg = "命中算话反欺诈高";
//							}
//						} else {
//							// 66666暂时不使用算话的结果，先注释掉，用的时候取消注释
//							// errorMsg.append("本地解析算话征信信息错误;");
//						}
//					} else {
//						// 66666暂时不使用算话的结果，先注释掉，用的时候取消注释
//						errorMsg.append("查询算话征信信息错误:" + serviceResult.getMsg() + ";");
//					}
				}
			}
			if (StringUtils.isBlank(reportId)) {
				ServiceResult serviceResult = tdService.getReport(params2);
				if (serviceResult.isSuccessed()) {
					reportId = serviceResult.getMsg();
				} else {
					errorMsg.append("生成同盾reportId失败;");
				}
			}
			if (StringUtils.isBlank(msg)) {
				if (StringUtils.isNotBlank(reportId)) {
					if (tdStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue()) {
						params2.put("reportId", reportId);
						ServiceResult serviceResult = tdService.queryReport(params2);
						if (serviceResult.isSuccessed()) {
							riskCreditUser = RiskCreditUserUtil.getInstance().createTd(id, serviceResult.getMsg(), reportId);
							if (riskCreditUser != null) {
								tdStatus = ConstantRisk.INTERFACE_SUC;
								riskCreditUserDao.updateTdDetail(riskCreditUser);
								if (tmp.getTdPhoneBlack() > 0) {
									msg = "命中同盾手机网贷黑名单";
								} else if (tmp.getTdCardNumBlack() > 0) {
									msg = "命中同盾身份证网贷黑名单";
								}
							} else {
								errorMsg.append("本地解析同盾征信信息错误;");
							}
						} else if ("600".equals(serviceResult.getCode())) {
							logger.info("td report is not ready wait for 3 seconds");
							try {
								Thread.sleep(5000l);
							} catch (Exception e) {
								logger.error(" wait td report agagin error", e);
							}
							params2.put("reportId", reportId);
							logger.info("td report after wait for 3 seconds send again");
							serviceResult = tdService.queryReport(params2);
							if (serviceResult.isSuccessed()) {
								riskCreditUser = RiskCreditUserUtil.getInstance().createTd(id, serviceResult.getMsg(), reportId);
								if (riskCreditUser != null) {
									tdStatus = ConstantRisk.INTERFACE_SUC;
									riskCreditUserDao.updateTdDetail(riskCreditUser);
									if (tmp.getTdPhoneBlack() > 0) {
										msg = "命中同盾手机网贷黑名单";
									} else if (tmp.getTdCardNumBlack() > 0) {
										msg = "命中同盾身份证网贷黑名单";
									}
								} else {
									errorMsg.append("本地解析同盾征信信息错误;");
								}
							} else {
								errorMsg.append("查询同盾征信信息错误:" + serviceResult.getMsg() + ";");
							}
						} else {
							errorMsg.append("查询同盾征信信息错误:" + serviceResult.getMsg() + ";");
						}

					}

				} else {
					errorMsg.append("同盾reportId缺失无法查询征信;");
				}
			}
			// 更新接口状态
			riskCreditUserDao.updateStatus(new RiskCreditUser(id, zmStatus, reportId, tdStatus, bqsStatus, jyStatus, mgStatus, zzcStatus, shStatus));
			serviceResult2 = new ServiceResult(ServiceResult.SUCCESS, "征信成功");
		} catch (Exception e) {
			logger.error("updateSendZx error id=" + id, e);
		} finally {
			if (StringUtils.isNotBlank(msg)) {
				serviceResult2.setCode("300");
				serviceResult2.setMsg(msg);
			}
		}
		return serviceResult2;
	}

	public String updateJudgeJc(RiskCreditUser riskCreditUser1, String dbTime, String result) {
		String  re="";
		Integer id = riskCreditUser1.getId();
		try {
			String presentAddress = riskCreditUser1.getPresentAddress();
			Integer presentAddNum = 0;
			if (StringUtils.isNotBlank(presentAddress)) {
				presentAddNum = riskCreditUserDao.findRepeatZz(presentAddress);
			}
			String companyAddress = riskCreditUser1.getCompanyAddress();
			Integer companyAddNum = 0;
			if (StringUtils.isNotBlank(companyAddress)) {
				companyAddNum = riskCreditUserDao.findRepeatGsdz(companyAddress);
			}
			String companyName = riskCreditUser1.getCompanyName();
			Integer companyNameNum = 0;
			if (StringUtils.isNotBlank(companyName)) {
				companyNameNum = riskCreditUserDao.findRepeatGsmc(companyName);
			}
			List<Integer> numList = riskCreditUserDao.findAllCount(riskCreditUser1);
			Integer companyPhoneDiffNameOrAdd = numList.get(0);
			Integer companyAddDiffNameOrPhone = numList.get(1);
			Integer companyNameDiffAddOrPhone = numList.get(2);
			if (companyPhoneDiffNameOrAdd.intValue() < 0) {
				companyPhoneDiffNameOrAdd = 0;
			}
			if (companyAddDiffNameOrPhone.intValue() < 0) {
				companyAddDiffNameOrPhone = 0;
			}
			if (companyNameDiffAddOrPhone.intValue() < 0) {
				companyNameDiffAddOrPhone = 0;
			}
			Integer manyDeviceLoginNum = numList.get(3);
			Integer concatApplyNum = numList.get(4);
			Integer oneDeviceRegManyPhoneNum = riskCreditUserDao.findDifPhoneByEqNum(riskCreditUser1.getEquipmentNumber());
			if (oneDeviceRegManyPhoneNum == null) {
				oneDeviceRegManyPhoneNum = 0;
			}
			if (companyNameNum == null) {
				companyNameNum = 0;
			}
			RiskCreditUser riskCreditUser3 = new RiskCreditUser(id, presentAddNum, companyAddNum, manyDeviceLoginNum, oneDeviceRegManyPhoneNum,
					companyNameNum, companyPhoneDiffNameOrAdd, companyAddDiffNameOrPhone, companyNameDiffAddOrPhone, concatApplyNum);
			int grayNum = riskCreditUserDao.findGray(riskCreditUser1);
			riskCreditUser3.setGrayNum(grayNum);
			riskCreditUserDao.updateJl(riskCreditUser3);
			RiskCreditUser riskCreditUser = riskCreditUserDao.findById(id);
			riskCreditUser.setJxlDetail(riskCreditUserDao.findDetailById(riskCreditUser.getUserId()));
			logger.error("zx primary id=" + id + ",after zr,lastDays=" + riskCreditUser.getLastDays());
			Date lastDate = riskCreditUserDao.findLastFail(riskCreditUser1.getUserId());
			if (lastDate != null) {
				Integer lastDays = -1;
				Date now = new Date();
				lastDays = DateUtil.daysBetween(lastDate, now);
				logger.error("zx primary id=" + id + ",query again,lastDays=" + lastDays);
				riskCreditUser.setLastDays(lastDays);
			}
			List<RiskManageRule> root = riskManageRuleService.findAllByRootType(RiskManageRule.ROOT_TYPE_ROOT);
			if (root != null && root.size() > 0) {
				Map<String, RiskManageRule> allRiskMap = SysCacheUtils.getAllRule();
				Map<String, String> baseMap = SysCacheUtils.getBaseRule();
				Map<String, String> propertyMap = SysCacheUtils.getConfigMap(ConstantRisk.BASE_RULE_PROPERTY);
				if (propertyMap != null && propertyMap.size() > 0) {
					for (String key : propertyMap.keySet()) {
						Object value = BeanReflectUtil.invokeGetMethod(RiskCreditUser.class, propertyMap.get(key), riskCreditUser);
						baseMap.put(key, value + "");
					}
					RiskCreditUserUtil.getInstance().findSon(root, allRiskMap, null);
					RiskManageRule riskManageRule = root.get(0);
					List<RiskRuleCal> calList = new ArrayList<RiskRuleCal>();
					RiskCreditUserUtil.getInstance().calSon2Parent(root, riskManageRule, baseMap, id, riskCreditUser.getAssetId(),
							riskCreditUser.getUserId(), calList);
					HashMap<String, Object> list = new HashMap<String, Object>();
					list.put("dbTime", dbTime);
					list.put("list", calList);
					riskRuleCalDao.batchInsert(list);
					if (riskManageRule != null) {
						String value = riskManageRule.getFormula(); 
						if (ConstantRisk.PASS_FORMULA.equals(value) || ConstantRisk.ED_LESS.equals(value)) {
							String msg = "";
							if (ConstantRisk.ED_LESS.equals(value)) {
								logger.info("before userId=" + riskCreditUser.getUserId() + " money is not pattern");
								// 重新计算订单表和更新征信表，同时记录原始申请金额
								BigDecimal money = new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP);
								BigDecimal[] array = money.divideAndRemainder(BigDecimal.valueOf(100));
								money = money.subtract(array[1]);
								msg = "申请借款金额：" + riskCreditUser.getMoneyAmount() + ",实际通过金额：" + money;
								BorrowOrder borrowOrder = new BorrowOrder();
								borrowOrder.setId(riskCreditUser.getAssetId());
								borrowOrder.setMoneyAmount(money.intValue());
								borrowOrderService.updateLoan(borrowOrder, riskCreditUser.getUserId());
								RiskCreditUser tmp = new RiskCreditUser();
								tmp.setId(riskCreditUser.getId());
								tmp.setMoneyAmount(money);
								riskCreditUserDao.updateBorrowMoney(tmp);
							}
							updateReviewSuc(dbTime, id, riskCreditUser, msg);
							re="1";
							
						} else {
							// 可能是复审也可能是拒绝
							String des = ConstantRisk.JC_RESULT.get(value);
							if (StringUtils.isBlank(des)) {
								des = value;
							}
							if (ConstantRisk.ED_UNKNOWN.equals(value)) {
								// 建议复审
								updateFirsReview(id, riskCreditUser.getAssetId(), des, ConstantRisk.RISK_STATUS_REVIEW, riskCreditUser1.getUserId(),
										dbTime);
							} else {
								// 机审拒绝
								updateFirsReview(id, riskCreditUser.getAssetId(), des, ConstantRisk.RISK_STATUS_FAIL, riskCreditUser1.getUserId(),
										dbTime);
							}
						}
					} else {
						logger.error("judgeJc error riskManageRule is null id=" + id);
					}
				}
			}
		} catch (Exception e) {
			logger.error("judgeJc error riskCreditUserId=" + id, e);
		}
		return re;
	}

	public void updateReviewSuc(String dbTime, Integer id, RiskCreditUser riskCreditUser, String msg) {
		// 通过
		String remark = "机审通过，可放款。" + msg;
		HashMap<String, Object> params2 = new HashMap<String, Object>();
		params2.put("remark", remark);
		riskCreditUser.setRiskCalSuf(dbTime);
		riskCreditUserDao.updateSuf(riskCreditUser);
		params2.put("id", riskCreditUser.getAssetId());
		riskCreditUserDao.updateAssetsSuc(params2);
		riskCreditUserDao.updateRiskStatus(new RiskCreditUser(id, ConstantRisk.RISK_STATUS_SUC, remark));
	}

	/**
	 * 判断准入原则
	 *
	 * @param uId            用户主键
	 * @param id             征信记录主键
	 * @param riskCreditUser
	 * @param assetId        借款记录表主键
	 * @return
	 */
	public boolean updateJudgeZr(Integer uId, Integer id, RiskCreditUser riskCreditUser, Integer assetId, String dbTime) {
		boolean zrFlag = true;
		String msg = "";
		try {
			int count = riskCreditUserDao.findBlack(riskCreditUser);
			// 命中本地黑名单，直接拒绝
			if (count > 0) {
				zrFlag = false;
				msg = "命中本库黑名单";
			} else {
				boolean allowSend = true;
				// 此处定义的值要set给传入的riskCreditUser对象，
				Integer yxMonth3Over = 0;
				Integer yxLessMonth3Over = 0;
				Integer yxFxNum = 0;
				// Integer zzcBlack = 2;
				// Integer zzcBlackNum = 0;
				// Integer zzcFqz = 3;
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("userId", uId);
				String sql = "yx_fx_num as yxFxNum,yx_month3_over as yxMonth3Over,yx_less_month3_over as yxLessMonth3Over,yx_time as yxTime,yx_status as yxStatus";
				// ",zzc_black as zzcBlack,zzc_black_num as zzcBlackNum,zzc_fqz as zzcFqz,zzc_fqz_id as zzcFqzId,zzc_black_time as zzcBlackTime,zzc_status as zzcStatus";
				params.put("sql", sql);
				RiskCreditUser tmp = riskCreditUserDao.findLastInterface(params);
				Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.INTERVAL);
				int interval = Integer.valueOf(intervalMap.get("INTERVAL_DAYS"));
				if (tmp != null) {
					if (tmp.getYxStatus().intValue() == 2 && DateUtil.daysBetween(tmp.getYxTime(), new Date()) <= interval) {
						allowSend = false;
						yxMonth3Over = tmp.getYxMonth3Over();
						yxLessMonth3Over = tmp.getYxLessMonth3Over();
						yxFxNum = tmp.getYxFxNum();
						tmp.setId(id);
						riskCreditUserDao.updateYx(tmp);
					}
				}
				if (allowSend) {
					// 宜信免费此处先调用宜信
					params.put("userId", uId);
					params.put("userName", riskCreditUser.getUserName());
					params.put("cardNum", riskCreditUser.getCardNum());
					ServiceResult serviceResult = yxService.sendYx(params);
					if (serviceResult.isSuccessed()) {
						RiskCreditUser riskCreditUser2 = RiskCreditUserUtil.getInstance().createYx(uId, serviceResult.getMsg());
						if (riskCreditUser2 != null) {
							yxMonth3Over = riskCreditUser2.getYxMonth3Over();
							yxLessMonth3Over = riskCreditUser2.getYxLessMonth3Over();
							yxFxNum = riskCreditUser2.getYxFxNum();
							riskCreditUser2.setId(id);
							riskCreditUserDao.updateYx(riskCreditUser2);
						} else {
							logger.info("judgeZr create yx return null");
						}
					}
					allowSend = true;
				}
			
				// }
				List<RiskManageRule> rootZr = riskManageRuleService.findAllByRootType(RiskManageRule.ROOT_TYPE_ROOT_ZR);
				// List<RiskManageRule> rootZr = SysCacheUtils.getZrRule();
				if (rootZr != null && rootZr.size() > 0) {
					Integer lastDays = -1;
					Date lastDate = riskCreditUserDao.findLastFail(uId);
					if (lastDate != null) {
						Date now = new Date();
						lastDays = DateUtil.daysBetween(lastDate, now);
					}
					logger.error("zx primary id=" + id + ",judge zr,lastDays=" + lastDays);
					riskCreditUser.setLastDays(lastDays);
					riskCreditUser.setYxMonth3Over(yxMonth3Over);
					riskCreditUser.setYxFxNum(yxFxNum);
					riskCreditUser.setYxLessMonth3Over(yxLessMonth3Over);
					// 更新聚信立和最近一次被拒日期距离当前的天数、最近一次逾期天数、历史逾期记录数到数据库
					riskCreditUser.setId(id);
					riskCreditUser.setLastDays(lastDays);
					riskCreditUserDao.updateJxlAndDays(riskCreditUser);
					// riskCreditUser.setZzcBlack(zzcBlack);
					// riskCreditUser.setZzcBlackNum(zzcBlackNum);
					// riskCreditUser.setZzcFqz(zzcFqz);
					Map<String, RiskManageRule> allRiskMap = SysCacheUtils.getAllRule();
					Map<String, String> baseMap = SysCacheUtils.getBaseRule();
					Map<String, String> propertyMap = SysCacheUtils.getConfigMap(ConstantRisk.BASE_RULE_PROPERTY);
					if (propertyMap != null && propertyMap.size() > 0) {
						for (String key : propertyMap.keySet()) {
							Object value = BeanReflectUtil.invokeGetMethod(RiskCreditUser.class, propertyMap.get(key), riskCreditUser);
							baseMap.put(key, value + "");
						}
						RiskCreditUserUtil.getInstance().findSon(rootZr, allRiskMap, null);
						RiskManageRule riskManageRule = rootZr.get(0);
						List<RiskRuleCal> calList = new ArrayList<RiskRuleCal>();
						RiskCreditUserUtil.getInstance().calSon2Parent(rootZr, riskManageRule, baseMap, id, assetId, uId, calList);
						HashMap<String, Object> list = new HashMap<String, Object>();
						list.put("dbTime", dbTime);
						list.put("list", calList);
						riskRuleCalDao.batchInsert(list);
						riskCreditUser.setRiskCalSuf(dbTime);
						riskCreditUserDao.updateSuf(riskCreditUser);
						if (riskManageRule != null) {
							if (ConstantRisk.PASS_FORMULA.equals(riskManageRule.getFormula())) {
								zrFlag = true;
							} else {
								zrFlag = false;
								msg = riskManageRule.getFormula();
							}
						} else {
							zrFlag = false;
							msg = "准入原则判定失败";
							logger.error("zr rule error riskManageRule is null userId=" + uId + ",id=" + id);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			zrFlag = false;
			msg = "准入原则发生未知异常";
			logger.error("judegeZr error ", e);
		} finally {
			if (!zrFlag) {
				updateFirsReview(id, assetId, msg, ConstantRisk.RISK_STATUS_FAIL, uId, dbTime);
			}

		}
		return zrFlag;
	}

	/**
	 * 修改初审状态(初审不通过，建议复审)
	 *
	 * @param id
	 * @param assetId
	 * @param remark
	 */
	public void updateFirsReview(Integer id, Integer assetId, String remark, Integer status, Integer userId, String dbTime) {
		try {
			HashMap<String, Object> params2 = new HashMap<String, Object>();
			params2.put("remark", remark);
			params2.put("id", assetId);
			String st = "";
			if (status.intValue() == ConstantRisk.RISK_STATUS_FAIL.intValue()) {
				st = "-3";
				// 审核拒绝后恢复可借金额
				riskCreditUserDao.updateUserAvailable(riskCreditUserDao.findBorrowMoney(id));
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("userId", userId);
				indexService.changeUserAmount(map);
			} else {
				st = "1";
			}

			RiskCreditUser riskCreditUser = new RiskCreditUser();
			riskCreditUser.setId(id);
			riskCreditUser.setRiskCalSuf(dbTime);
			riskCreditUserDao.updateSuf(riskCreditUser);
			params2.put("st", st);
			riskCreditUserDao.updateAssetsFail(params2);
			riskCreditUserDao.updateRiskStatus(new RiskCreditUser(id, status, remark));
		} catch (Exception e) {
			logger.error("updateFirsReview error id=" + id + ",assetId=" + assetId, e);
		}
	}

	@Override
	public void updateAll(HashMap<String, Object> params, boolean sendRisk) {
		// 用户表主键ID更新用户表专用
		Object userId = params.get("userId");
		Object userName = params.get("userName");
		Object cardNum = params.get("cardNum");
		Object userPhone = params.get("userPhone");
		// 征信表主键ID，更新征信表使用
		Object objId = params.get("id");
		// 借款信息表的主键ID
		Object objAssetId = params.get("assetId");
		// 征信失败返回的消息
		StringBuffer errorMsg = new StringBuffer();
		// 征信成功返回的命中禁止项的信息
		StringBuffer msg = new StringBuffer();
		Integer uId = null;
		Integer id = null;
		Integer assetId = null;
		String dbTime = riskRuleCalDao.findDbTime();
		try {
			if (userId != null && userName != null && cardNum != null && userPhone != null && objId != null && objAssetId != null) {
				uId = Integer.valueOf(userId + "");
				id = Integer.valueOf(objId + "");
				assetId = Integer.valueOf(objAssetId + "");
				RiskCreditUser riskCreditUser = riskCreditUserDao.findUserDetail(uId);
				if (updateJudgeZr(uId, id, riskCreditUser, assetId, dbTime)) {
					RiskCreditUser riskCreditUser2 = riskCreditUserDao.findInterfaceStatus(id);
					Integer tdStatus = riskCreditUser2.getTdStatus();
					Integer bqsStatus = riskCreditUser2.getBqsStatus();
					Integer jyStatus = riskCreditUser2.getJyStatus();
					Integer mgStatus = riskCreditUser2.getMgStatus();
					Integer zmStatus = riskCreditUser2.getZmStatus();
					Integer zzcStatus = riskCreditUser2.getZzcStatus();
					String reportId = riskCreditUser2.getTdReportId();
					Integer zmIndustyBlack = riskCreditUser.getZmIndustyBlack();
					Integer zmOver = riskCreditUser.getZmOver();
					Integer zmNoPayOver = riskCreditUser.getZmNoPayOver();
					Integer shStatus = riskCreditUser2.getShStatus();
					BigDecimal zmScore = riskCreditUser.getZmScore();
					boolean tdAllow = true;
					boolean bqsAllow = true;
					boolean jyAllow = true;
					boolean mgAllow = true;
					boolean zmAllow = true;
					boolean zzcAllow = true;
					boolean shAllow = true;
					if (riskCreditUser2.getRiskStatus().intValue() == ConstantRisk.RISK_STATUS_WAIT.intValue()) {
						Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.INTERVAL);
						int interval = Integer.valueOf(intervalMap.get("INTERVAL_DAYS"));
						// 新用户才有可能存在两天内二次调用可能（二次分别是1.刚认证完计算过额度，2.借款）
						// if (riskCreditUser.getCustomerType().intValue() == 0)
						// {
						params.put("userId", uId);
						String sql = "id,user_id as userId,asset_id as assetId,td_report_id as tdReportId,td_report_time as tdReportTime,td_score as tdScore,td_phone_black as tdPhoneBlack,"
								+ "td_card_num_black as tdCardNumBlack,td_month1_borrow as tdMonth1Borrow,td_day7_borrow as tdDay7Borrow,td_month1_card_num_device_borrow as tdMonth1CardNumDeviceBorrow,"
								+ "td_day7_device_card_or_phone_borrow as tdDay7DeviceCardOrPhoneBorrow,td_day7_card_device as tdDay7CardDevice,"
								+ "td_month3_apply_card as tdMonth3ApplyCard,td_month3_card_apply as tdMonth3CardApply,"
								+ "zm_score as zmScore,zm_score_time as zmScoreTime,zm_industy_black as zmIndustyBlack,zm_over as zmOver,zm_no_pay_over as zmNoPayOver,"
								+ "zm_industy_time as zmIndustyTime,bqs_black as bqsBlack,bqs_black_time as bqsBlackTime,jy_loan_num as jyLoanNum,jy_jd_num as jyJdNum,jy_jd_bl as jyJdBl,"
								+ "jy_over_num as jyOverNum,jy_over_bl as jyOverBl,jy_fk_num as jyFkNum,jy_hk_num as jyHkNum,jy_hk_bl as jyHkBl,jy_time as jyTime,"
								+ "mg_black_score as mgBlackScore,mg_day7_num as mgDay7Num,mg_month1_num as mgMonth1Num,mg_black as mgBlack,mg_time as mgTime"
								+ ",zzc_black as zzcBlack,zzc_black_num as zzcBlackNum,zzc_fqz as zzcFqz,zzc_fqz_id as zzcFqzId,zzc_black_time as zzcBlackTime,zzc_status as zzcStatus,"
								+ "sh_fqz as shFqz,sh_score as shScore,sh_status as shStatus,sh_time as shTime";
						params.put("sql", sql);
						RiskCreditUser tmp = riskCreditUserDao.findLastInterface(params);
						if (tmp != null) {
							if (tmp.getZzcStatus().intValue() == 2 && tmp.getZzcBlackTime() != null
									&& DateUtil.daysBetween(tmp.getZzcBlackTime(), new Date()) <= interval) {
								zzcAllow = false;
								tmp.setId(id);
								riskCreditUserDao.updateZzc(tmp);
								zzcStatus = ConstantRisk.INTERFACE_SUC;
								if (tmp.getZzcBlack().intValue() == 1) {
									msg.append("命中中智诚黑名单;");
								}
								if (tmp.getZzcFqz().intValue() == 1) {
									msg.append("命中中智诚反欺诈高;");
								}
							}
							if (msg.length() == 0 && tmp.getTdReportTime() != null
									&& DateUtil.daysBetween(tmp.getTdReportTime(), new Date()) <= interval) {
								reportId = tmp.getTdReportId();
								if (StringUtils.isNotBlank(reportId)) {
									tdAllow = false;
									tmp.setId(id);
									riskCreditUserDao.updateTdDetail(tmp);
									tdStatus = ConstantRisk.INTERFACE_SUC;
									if (tmp.getTdPhoneBlack() > 0) {
										msg.append("命中同盾手机网贷黑名单;");
									}
									if (tmp.getTdCardNumBlack() > 0) {
										msg.append("命中同盾身份证网贷黑名单;");
									}
								}

							}
							if (msg.length() == 0 && tmp.getZmScoreTime() != null
									&& DateUtil.daysBetween(tmp.getZmScoreTime(), new Date()) <= interval) {
								zmAllow = false;
								zmScore = tmp.getZmScore();
								zmIndustyBlack = tmp.getZmIndustyBlack();
								zmOver = tmp.getZmOver();
								zmNoPayOver = tmp.getZmNoPayOver();
								riskCreditUser.setId(id);
								riskCreditUser.setUserId(uId);
								riskCreditUser.setZmScore(zmScore);
								riskCreditUser.setZmIndustyBlack(zmIndustyBlack);
								riskCreditUser.setZmOver(zmOver);
								riskCreditUser.setZmNoPayOver(zmNoPayOver);
								riskCreditUserDao.updateZm(riskCreditUser);
								zmStatus = ConstantRisk.INTERFACE_SUC;
								if (riskCreditUser.getZmIndustyBlack().intValue() == 1) {
									msg.append("命中芝麻信用黑名单;");
								}
							}
							if (tmp.getBqsBlackTime() != null && DateUtil.daysBetween(tmp.getBqsBlackTime(), new Date()) <= interval) {
								bqsAllow = false;
								tmp.setId(id);
								riskCreditUserDao.updateBqs(tmp);
								bqsStatus = ConstantRisk.INTERFACE_SUC;
								if (tmp.getBqsBlack().intValue() == 2) {
									msg.append("命中白骑士黑名单;");
								}
							}
							if (msg.length() == 0 && tmp.getJyTime() != null && DateUtil.daysBetween(tmp.getJyTime(), new Date()) <= interval) {
								jyAllow = false;
								tmp.setId(id);
								riskCreditUserDao.updateJy(tmp);
								jyStatus = ConstantRisk.INTERFACE_SUC;
								bqsStatus = ConstantRisk.INTERFACE_SUC;
								if (tmp.getJyOverNum().intValue() > 0) {
									msg.append("命中91逾期记录;");
								}
							}
							if (tmp.getMgTime() != null && DateUtil.daysBetween(tmp.getMgTime(), new Date()) <= interval) {
								mgAllow = false;
								tmp.setId(id);
								riskCreditUserDao.updateMg(tmp);
								mgStatus = ConstantRisk.INTERFACE_SUC;
								if (tmp.getMgBlack().intValue() == 1) {
									msg.append("命中蜜罐黑名单;");
								}
							}
							if (tmp.getShTime() != null && DateUtil.daysBetween(tmp.getShTime(), new Date()) <= interval) {
								shAllow = false;
								tmp.setId(id);
								riskCreditUserDao.updateSh(tmp);
								mgStatus = ConstantRisk.INTERFACE_SUC;
								if (tmp.getShFqz().intValue() == 3) {
									// 66666暂时不使用算话的结果，先注释掉，用的时候取消注释
									// msg.append("命中算话反欺诈高;");
								}
							}
						}
						// }
						if (msg.length() == 0) {
							// 查询各个接口状态曾经的状态
							HashMap<String, Object> params2 = new HashMap<String, Object>();
							params2.putAll(params);
							if (zzcStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue() && zzcAllow) {
							params.put("userId", uId);
								params.put("userName", riskCreditUser.getUserName());
								params.put("cardNum", riskCreditUser.getCardNum());
								params.put("userPhone", riskCreditUser.getUserPhone());
								ServiceResult serviceResult = zzcService.getFqz(params);
								if (serviceResult.isSuccessed()) {
//									JSONObject jsonObject = JSONObject.fromObject(serviceResult.getMsg());
//									String zzcId = jsonObject.getString("id");
//									params.put("zzcId", zzcId);
//									serviceResult = zzcService.findFqz(params);
//									if (serviceResult.isSuccessed()) {
										RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createZzc(id, serviceResult.getMsg());
										if (riskCreditUser3 != null) {
											zzcStatus = ConstantRisk.INTERFACE_SUC;
											//riskCreditUser3.setZzcFqzId(zzcId);
											riskCreditUserDao.updateZzc(riskCreditUser3);
											if (riskCreditUser3.getZzcBlack().intValue() == 1) {
												msg.append("命中中智诚黑名单;");
											}
//											if (riskCreditUser3.getZzcFqz().intValue() == 1) {
//												msg.append("命中中智诚反欺诈高;");
//											}
										} else {
											errorMsg.append("本地解析中智诚征信信息错误;" + serviceResult.getMsg());
											logger.error("query zzc report error" + serviceResult);
										}
//									} else {
//										errorMsg.append("查询中智诚反欺诈征信信息错误;" + serviceResult.getMsg());
//										logger.error("query zzc report error" + serviceResult.toString());
//									}
								} else {
									errorMsg.append("查询中智诚反欺诈ID征信信息错误;" + serviceResult.getMsg());
									logger.error("create zzc id error" + serviceResult.toString());
								}
							}
							if (msg.length() == 0 && zmStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue() && zmAllow) {
								ServiceResult serviceResult = zmxyService.getOpenId(params2);
								if (serviceResult.isSuccessed()) {
									// 成功获得openId则查询最新芝麻分
									String opendId = serviceResult.getMsg();
									params2.put("openId", opendId);
									serviceResult = zmxyService.getZmScore(params2);
									if (serviceResult.isSuccessed()) {
										// 获取芝麻分成功则更新最新芝麻分到用户表
										zmScore = new BigDecimal(serviceResult.getMsg());
									}
									serviceResult = zmxyService.getCreditWatchList(params2);
									if (serviceResult.isSuccessed()) {
										RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createZm(uId, serviceResult.getMsg());
										zmIndustyBlack = riskCreditUser3.getZmIndustyBlack();
										zmOver = riskCreditUser3.getZmOver();
										zmNoPayOver = riskCreditUser3.getZmNoPayOver();
									}
								}
								riskCreditUser.setId(id);
								riskCreditUser.setUserId(uId);
								riskCreditUser.setZmScore(zmScore);
								riskCreditUser.setZmIndustyBlack(zmIndustyBlack);
								riskCreditUser.setZmOver(zmOver);
								riskCreditUser.setZmNoPayOver(zmNoPayOver);
								riskCreditUserDao.updateUserZm(riskCreditUser);
								riskCreditUserDao.updateZm(riskCreditUser);
								zmStatus = ConstantRisk.INTERFACE_SUC;
								if (riskCreditUser.getZmIndustyBlack().intValue() == 1) {
									msg.append("命中芝麻信用黑名单;");
								}
							}
							// 白骑士黑名单接口
							if (bqsStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue() && bqsAllow) {
								ServiceResult serviceResult = bqsService.getRisk(params2);
								if (serviceResult.isSuccessed()) {
									RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createBqs(id, serviceResult.getMsg());
									if (riskCreditUser3 != null) {
										bqsStatus = ConstantRisk.INTERFACE_SUC;
										riskCreditUserDao.updateBqs(riskCreditUser3);
										if (riskCreditUser3.getBqsBlack().intValue() == 2) {
											msg.append("命中白骑士黑名单;");
										}
									} else {
										errorMsg.append("本地解析白骑士征信信息错误;");
									}
								} else {
									errorMsg.append("查询白骑士征信信息错误:" + serviceResult.getMsg() + ";");
								}
							}
							if (msg.length() == 0 && jyStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue() && jyAllow) {
								ServiceResult serviceResult = jyzxService.getBorrow(params2);
								if (serviceResult.isSuccessed()) {
									RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createJyzx(id, serviceResult.getMsg());
									if (riskCreditUser3 != null) {
										jyStatus = ConstantRisk.INTERFACE_SUC;
										riskCreditUserDao.updateJy(riskCreditUser3);
										if (riskCreditUser3.getJyOverNum().intValue() > 0) {
											msg.append("命中91逾期记录;");
										}
									} else {
										errorMsg.append("本地解析91征信信息错误;");
									}
								} else {
									errorMsg.append("查询91征信信息错误:" + serviceResult.getMsg() + ";");
								}
							}
							if (mgStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue() && mgAllow) {
								ServiceResult serviceResult = jxlMgService.getDetail(params2);
								if (serviceResult.isSuccessed()) {
									RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createMg(id, serviceResult.getMsg());
									if (riskCreditUser3 != null) {
										mgStatus = ConstantRisk.INTERFACE_SUC;
										riskCreditUserDao.updateMg(riskCreditUser3);
										if (riskCreditUser3.getMgBlack().intValue() == 1) {
											msg.append("命中蜜罐黑名单;");
										}
									} else {
										errorMsg.append("本地解析密罐征信信息错误;");
									}
								} else {
									errorMsg.append("查询密罐征信信息错误:" + serviceResult.getMsg() + ";");
								}
							}
							if (shStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue() && shAllow) {
								//本系统不适用算话
						/*		ServiceResult serviceResult = shService.getFqz(params2);
								if (serviceResult.isSuccessed()) {
									RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createSh(id, serviceResult.getMsg());
									if (riskCreditUser3 != null) {
										shStatus = ConstantRisk.INTERFACE_SUC;
										riskCreditUserDao.updateSh(riskCreditUser3);
										if (riskCreditUser3.getShFqz().intValue() == 3) {
											// 66666暂时不使用算话的结果，先注释掉，用的时候取消注释
											// msg.append("命中算话反欺诈高;");
										}
									} else {
										// 66666暂时不使用算话的结果，先注释掉，用的时候取消注释
										// errorMsg.append("本地解析算话征信信息错误;");
									}
								} else {
									// 66666暂时不使用算话的结果，先注释掉，用的时候取消注释
									// errorMsg.append("查询算话征信信息错误:" +
									// serviceResult.getMsg() + ";");
								}*/
							}
							// 同盾明确告知是生成reportId到时候产生费用
							if (msg.length() == 0 && tdAllow) {
								ServiceResult serviceResult = tdService.getReport(params2);
								if (serviceResult.isSuccessed()) {
									reportId = serviceResult.getMsg();
								} else {
									errorMsg.append("生成同盾reportId失败;");
								}
							}
							if (msg.length() == 0 && StringUtils.isNotBlank(reportId)) {
								if (tdStatus.intValue() != ConstantRisk.INTERFACE_SUC.intValue() && tdAllow) {
									params2.put("reportId", reportId);
									ServiceResult serviceResult = tdService.queryReport(params2);
									if (serviceResult.isSuccessed()) {
										RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createTd(id, serviceResult.getMsg(),
												reportId);
										if (riskCreditUser3 != null) {
											tdStatus = ConstantRisk.INTERFACE_SUC;
											riskCreditUserDao.updateTdDetail(riskCreditUser3);
											if (riskCreditUser3.getTdPhoneBlack() > 0) {
												msg.append("命中同盾手机网贷黑名单;");
											}
											if (riskCreditUser3.getTdCardNumBlack() > 0) {
												msg.append("命中同盾身份证网贷黑名单;");
											}
										} else {
											errorMsg.append("本地解析同盾征信信息错误;");
										}
									} else if ("600".equals(serviceResult.getCode())) {
										logger.info("td report is not ready wait for 3 seconds");
										Thread.sleep(5000l);
										params2.put("reportId", reportId);
										logger.info("td report after wait for 3 seconds send again");
										serviceResult = tdService.queryReport(params2);
										if (serviceResult.isSuccessed()) {
											RiskCreditUser riskCreditUser3 = RiskCreditUserUtil.getInstance().createTd(id, serviceResult.getMsg(),
													reportId);
											if (riskCreditUser3 != null) {
												tdStatus = ConstantRisk.INTERFACE_SUC;
												riskCreditUserDao.updateTdDetail(riskCreditUser3);
												if (riskCreditUser3.getTdPhoneBlack() > 0) {
													msg.append("命中同盾手机网贷黑名单;");
												}
												if (riskCreditUser3.getTdCardNumBlack() > 0) {
													msg.append("命中同盾身份证网贷黑名单;");
												}
											} else {
												errorMsg.append("本地解析同盾征信信息错误;");
											}
										} else {
											errorMsg.append("查询同盾征信信息错误:" + serviceResult.getMsg() + ";");
										}
									} else {
										errorMsg.append("查询同盾征信信息错误:" + serviceResult.getMsg() + ";");
									}

								}
							} else {
								errorMsg.append("同盾reportId缺失无法查询征信;");
							}
						}
						// 更新接口状态
						riskCreditUserDao.updateStatus(new RiskCreditUser(id, zmStatus, reportId, tdStatus, bqsStatus, jyStatus, mgStatus, zzcStatus,
								shStatus));
						// 写入redis
						if (sendRisk) {
//							if (false) {
							// 1是，2不是黑名单
							int black = 2;
							if (msg.length() > 0) {
								black = 1;
							}
							
							String value = updateCalUserMoney(id, dbTime);
							updateJudgeJc(riskCreditUser, dbTime, value);
							
//							String data = "{\"uId\":\"" + userId + "\",\"rId\":\"" + id + "\",\"flag\":\"" + 1 + "\",\"cType\":\"" + riskCreditUser.getCustomerType()
//									+ "\",\"bId\":\"" + assetId + "\",\"blk\":\"" + black + "\",\"dbt\":\"" + dbTime + "\"}";
//							sendToRisk(data, id);
							
							if (black == 1) {
								updateFirsReview(id, assetId, msg.toString(), ConstantRisk.RISK_STATUS_FAIL, uId, dbTime);
							}
							// 更新数据库。
						} else {
							if (msg.length() == 0) {
								if (errorMsg != null && errorMsg.length() > 0) {
									riskCreditUser.setRiskCalSuf(dbTime);
									riskCreditUserDao.updateSuf(riskCreditUser);
									// 调用征信接口报错
									updateFirsReview(id, assetId, errorMsg.toString(), ConstantRisk.RISK_STATUS_REVIEW_ZX_EXCEPTION, uId, dbTime);
								} else {
									String value = updateCalUserMoney(id, dbTime);
									// 所有接口成功，考虑运算决策树
									//查看是否是老用户 如果是老用户 并且老用户开关已经打开 那么 进入人工审核
									if (!sendRisk) {
										
										String re=updateJudgeJc(riskCreditUser, dbTime, value);
										if("1".equals(re)){
											String oldstatus = saveUpdateBorrowTGJS(assetId);
											logger.info("老用户跳过机审 oldstatus " + oldstatus);
										}
									}/* else {
										updateJudgeJc(riskCreditUser, dbTime, value);
									}*/
								}
							} else {
								updateFirsReview(id, assetId, msg.toString(), ConstantRisk.RISK_STATUS_FAIL, uId, dbTime);
							}
						}
					}
				}
			} else {
				logger.error("updateAll params is not enough,params=" + params);
			}
		} catch (Exception e) {
			logger.error("updateAll error params=" + params, e);
			updateFirsReview(id, assetId, "机审准入原则未知异常", ConstantRisk.RISK_STATUS_REVIEW_EXCEPTION, uId, dbTime);
		}
	}

	/**
	 * 老用户开关 , 跳过机器审核 直接进入人工复审核
	 *
	 * @param id
	 * @return
	 */
	public String saveUpdateBorrowTGJS(Integer id) {
		String key = BorrowOrder.REVIEW_BORROW + id;
		String value = key;
		jedisCluster.setex(key, BorrowOrder.REVIEW_BORROW_SECOND, value);
		BorrowOrder borrowOrderR = borrowOrderService.findOneBorrow(id);
		//只有待机审的老用户才能跳过
		if (borrowOrderR.getStatus().intValue() == BorrowOrder.STATUS_DCS
				&& 1 == borrowOrderR.getCustomerType()) {
			BorrowOrder borrowOrder = new BorrowOrder();
			borrowOrder.setId(id);
			borrowOrder.setUpdatedAt(new Date());

			borrowOrder.setStatus(BorrowOrder.STATUS_CSTG);
			borrowOrder.setRemark("该用户是老用户, 机器操作跳过机审！");

			borrowOrder.setVerifyTrialTime(new Date());
			borrowOrder.setVerifyTrialRemark(borrowOrder.getRemark());
			borrowOrder.setVerifyTrialUser("系统自动");

			borrowOrderService.updateById(borrowOrder);
			//tsOrdersService.sendBorrowStatus(borrowOrder.getId());

			if (borrowOrderR.getStatus() == BorrowOrder.STATUS_DCS) {
				RiskCreditUser riskCreditUser = new RiskCreditUser();
				riskCreditUser.setAssetId(borrowOrderR.getId());
				riskCreditUser.setRiskStatus(6);
				borrowOrderService.updateRiskCreditUserById(riskCreditUser);
			}

			return "系统跳过机器审核成功 borrowOrder id = " + id;
		}
		return "非待机审的老用户无法机审 borrowOrder id = " + id;
	}

public static void main(String[] args) {
	String dd="{\"uId\":\"40\",\"rId\":\"30\",\"flag\":\"1\",\"cType\":\"0\",\"bId\":\"19\",\"blk\":\"2\",\"dbt\":\"20170918\"}";
	JSONObject jsonObject = JSONObject.fromObject(dd);
	int flag = jsonObject.getInt("flag");
	int id = jsonObject.getInt("rId");
	int bId = jsonObject.getInt("bId");
	int uId = jsonObject.getInt("uId");
	String dbTime = jsonObject.getString("dbt");
}
	@Override
	public void updateFromRisk() {
		System.out.println("******************开始执行***************************");
		//风控审核
		String value = "";
		try {
			value = JedisDataClientFK.rpop(riskIt);
			logger.info("updateFromRisk info data=" + value);
			while (value != null) {
				logger.info(" info not null data=" + value);
				final String tmp = value;
				ThreadPool2.getInstance().run(new Runnable() {
					@Override
					public void run() {
						JSONObject jsonObject = JSONObject.fromObject(tmp);
						int flag = jsonObject.getInt("flag");
						int id = jsonObject.getInt("rId");
						int bId = jsonObject.getInt("bId");
						int uId = jsonObject.getInt("uId");
						String dbTime = jsonObject.getString("dbt");
						// 发送给新模型之前如果没有命中黑名单则以新模型结果为准(更新审核状态),否则只记录返回状态
						if ("2".equals(jsonObject.get("blk"))) {
							// 通过，调用审核通过的方法
							if (flag == 1) {
								//
								RiskCreditUser tmp = new RiskCreditUser();
								tmp.setRiskCalSuf(dbTime);
								tmp.setAssetId(bId);
								updateReviewSuc(dbTime, id, tmp, "新风控审核通过");
							} else {
								// 不通过,调用原本审核不通过的方法
								updateFirsReview(id, bId, "新风控反馈审核不通过", ConstantRisk.RISK_STATUS_FAIL, uId, dbTime);
							}
						}
//						riskCreditUserDao.updateNewRisk(new RiskCreditUser(id, tmp, new BigDecimal(jsonObject.getString("score")), flag));
						riskCreditUserDao.updateNewRisk(new RiskCreditUser(id, tmp, new BigDecimal(0), flag));
					}
				});
				value = JedisDataClientFK.rpop(riskOt);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendToRisk(String data, Integer id) {
		try {
			logger.info("sendToRisk info data=" + data);
			riskCreditUserDao.updateRiskStatus(new RiskCreditUser(id, ConstantRisk.RISK_STATUS_WAIT_NEW, "等待新模型反馈审核结果"));
			JedisDataClientFK.setList(riskIt, data);
		} catch (Exception e) {
			logger.error("sendToRisk error data=" + data, e);
		}
	}

	@Override
	public int updateZmScore(RiskCreditUser riskCreditUser) {
		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.GET_SCORE,
		// ConstantRisk.ZMXY));
		return riskCreditUserDao.updateUserZmScore(riskCreditUser);
		// riskCreditUserDao.updateZmScore(riskCreditUser);
	}

	@Override
	public int updateTdDetail(RiskCreditUser riskCreditUser) {
		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.TD_PRELOAN_REPORT,
		// ConstantRisk.TD));

		return riskCreditUserDao.updateTdDetail(riskCreditUser);
	}

	@Override
	public int updateBqs(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getId(),
		// riskCreditUser.toString(), ConstantRisk.BQS_RISK,
		// ConstantRisk.BQS));
		return riskCreditUserDao.updateBqs(riskCreditUser);
	}

	@Override
	public int updateJy(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.JYZX_BORROW,
		// ConstantRisk.JYZX));
		return riskCreditUserDao.updateJy(riskCreditUser);
	}

	@Override
	public int updateMg(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.MG_BLACK,
		// ConstantRisk.MG));
		return riskCreditUserDao.updateMg(riskCreditUser);
	}

	@Override
	public int updateJxl(RiskCreditUser riskCreditUser) {

		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.JXL_ANALYSIS,
		// ConstantRisk.JXL));
		riskCreditUserDao.updateUserJxl(riskCreditUser);
		return riskCreditUserDao.updateNewFlag(riskCreditUser.getUserId());
		// riskCreditUserDao.updateJxl(riskCreditUser);
	}

	@Override
	public List<RiskRuleProperty> findRuleProperty(HashMap<String, Object> params) {
		return riskCreditUserDao.findRuleProperty(params);
	}

	@Override
	public int updateJxlToken(RiskCreditUser riskCreditUser) {
		// riskCreditLogDao.insert(new RiskCreditLog(riskCreditUser.getUserId(),
		// riskCreditUser.toString(), ConstantRisk.GET_TOKEN,
		// ConstantRisk.JXL));
		// riskCreditUserDao.updateJxlToken(riskCreditUser);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userId", riskCreditUser.getUserId());
		this.infoIndexService.authMobile(map);// 初始设置
		return riskCreditUserDao.updateUserJxlToken(riskCreditUser);
	}

	@Override
	public List<RiskCreditUser> findByUserId(Integer userId) {
		return riskCreditUserDao.findByUserId(userId);
	}

	@Override
	public PageConfig<HashMap<String, Object>> findJxlPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "RiskCreditUser");
		return paginationDao.findPage("findJxlWaitReport", "findJxlWaitReportCount", params, "risk");
	}

	@Override
	public PageConfig<HashMap<String, Object>> findAnalysisPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "RiskCreditUser");
		return paginationDao.findPage("findWaitAnalysis", "findWaitAnalysisCount", params, "risk");
	}

	@Override
	public PageConfig<RiskCreditUser> findCalPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "RiskCreditUser");
		return paginationDao.findPage("findCalMoney", "findCalMoneyCount", params, "risk");
	}
}
